package register;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.UpdatePasswordCallback;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import co.yeye.test.MainActivity;
import co.yeye.test.R;
import models.UserObject;

/**
 * Created by yeye on 15/2/26.
 */
public class UserModify extends Activity {

    Button btn_modify,tittle;
    EditText username,origin_pwk,new_pwk,new_pwk_repeat;
    ImageView img;

    AVObject avObject;
    private String new_img_url="-1";
    int successNum=0,currentNum=0;       // 成功的项目
    ImageLoader imageLoader;
    DisplayImageOptions options;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==100){
                String sdStatus = Environment.getExternalStorageState();
                if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                    Log.i("TestFile",
                            "SD card is not avaiable/writeable right now.");
                    return;
                }
                String name = new DateFormat().format("yyyyMMdd_hhmmss",
                        Calendar.getInstance(Locale.CHINA)) + ".jpg";
                //Toast.makeText(this, name, Toast.LENGTH_LONG).show();
                Bundle bundle = data.getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式

                FileOutputStream b = null;
                File file = new File("/sdcard/.MyOptoUploadImg/");
                file.mkdirs();// 创建文件夹
                String fileName = "/sdcard/.MyOptoUploadImg/"+name;

                try {
                    b = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        b.flush();
                        b.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //bitmapList.add(bitmap);
                //Toast.makeText(getBaseContext(),fileName,Toast.LENGTH_SHORT).show();
                new_img_url = fileName;
                // 配置图片
                imageLoader.displayImage("file://"+new_img_url,img,options,null);
            }
        }
        // 图片
        if(resultCode==RESULT_OK){
            if(requestCode==101){
                new_img_url = data.getData().toString();
                imageLoader.displayImage(new_img_url,img,options,null);
                new_img_url = GetPathByUri.getPath(getBaseContext(), data.getData());
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_modify);

        UserObject userObject = MainActivity.getInstance().getUser();
        AVQuery<AVObject> query = new AVQuery<AVObject>("_User");
        query.whereEqualTo("username", userObject.getUser_name());
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> avObjects, AVException e) {
                if(e==null)
                    avObject=avObjects.get(0);
            }
        });

        img = (ImageView) findViewById(R.id.user_img);
        btn_modify = (Button) findViewById(R.id.btn_modify);
        tittle = (Button) findViewById(R.id.tittle);
        username = (EditText) findViewById(R.id.username);
        origin_pwk = (EditText) findViewById(R.id.origin_pwk);
        new_pwk = (EditText) findViewById(R.id.new_pwk);
        new_pwk_repeat = (EditText) findViewById(R.id.new_pwk_repeat);
        tittle.setVisibility(View.GONE);

        imageLoader = MainActivity.getInstance().getImageLoader();
        options = MainActivity.getInstance().getOptionCache();

        // 显示用户头像
        String url = MainActivity.getInstance().getUser().getUri();
        imageLoader.displayImage(url,img,options,null);

        btn_modify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(avObject==null)
                    return;
                currentNum=0;
                successNum=0;
                // 统计
                if(username.getText().length()!=0)
                    successNum++;
                if(origin_pwk.getText().length()!=0)
                    successNum++;
                if(!new_img_url.equals("-1"))
                    successNum++;
                // 需要修改用户名
                if(origin_pwk.getText().length()!=0) {
                    //successNum++;
                    modifyPwk();
                }
                if(username.getText().length()!=0){
                    //successNum++;
                    modifyUserName();
                }
                if(!new_img_url.equals("-1")) {
                    //successNum++;
                    modifyImg();
                }
            }
        });

        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 让用户选择拍照还是本地选取图片
                AlertDialog alertDialog = new AlertDialog.Builder(UserModify.this)
                        .setTitle("选择图片来源")
                        .setNegativeButton("拍照",new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(intent,100);
                            }
                        })
                        .setPositiveButton("图库",new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                intent.setType("image/*");
                                //intent.putExtra("crop", "true");
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 101);
                            }
                        })
                        .show();
            }
        });
    }

    private void modifyUserName(){
        avObject.put("username",username.getText().toString());
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if(e==null) {
                    currentNum++;
                    commitDone();
                }
                else
                    setTittle("用户名重复",getResources().getColor(R.color.red),3000,false);
            }
        });
    }

    private void modifyImg(){
        AVFile avFile = new AVFile();
        try {
            avFile = AVFile.withAbsoluteLocalPath("head", new_img_url);
        }catch(IOException e){
            e.printStackTrace();
            Toast.makeText(getBaseContext(),e.toString(),Toast.LENGTH_SHORT).show();
            return;
        }
        avObject.put("user_img",avFile);
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if(e==null) {
                    currentNum++;
                    commitDone();
                }
            }
        });
    }

    private void modifyPwk(){
        // 密码是否已填写
        if(origin_pwk.getText().length()==0 || new_pwk.getText().length()==0 ||
                new_pwk_repeat.getText().length()==0){
            setTittle("请输入原密码和新密码",getResources().getColor(R.color.red),3000,false);
            return;
        }
        // 两次密码是否相同
        if(!new_pwk.getText().toString().equals(new_pwk_repeat.getText().toString())){
            setTittle("两次输入的密码不相同",getResources().getColor(R.color.red),3000,false);
            return;
        }
        // 验证原密码是否正确
        //UserObject user = MainActivity.getInstance().getUser();
        AVUser avUser = new AVUser();
        avUser = AVUser.getCurrentUser();
        if(avUser!=null){
            avUser.updatePasswordInBackground(origin_pwk.getText().toString(),
                    new_pwk.getText().toString(),new UpdatePasswordCallback() {
                        @Override
                        public void done(AVException e) {
                            if(e==null){
                                currentNum++;
                                commitDone();
                            }
                            else {
                                setTittle("网络故障或原密码错误", getResources().getColor(R.color.red), 3000, false);
                                Log.v("YeYe",e.toString());
                            }
                        }
                    });
        }
    }

    private void commitDone(){
        if(currentNum==successNum) {
            Log.v("YeYe","Done");
            setResult(RESULT_OK);
            MainActivity.getInstance().logOut();
            finish();
            /*
            AVUser avUser = new AVUser();
            avUser.logOut();
            avUser.logInInBackground(username.getText().toString(), new_pwk.getText().toString(),
                    new LogInCallback<AVUser>() {
                        @Override
                        public void done(AVUser avUser, AVException e) {
                            if(e!=null)
                                setTittle("错误",getResources().getColor(R.color.red),2000,false);
                        }
                    });
            avUser.getCurrentUser();
            AVFile avFile = avUser.getAVFile("user_img");
            String uri = avFile.getUrl();
            String username = avUser.getString("username");
            //MainActivity.getInstance().setSlideInfo(uri,username,null,null);

            // 保存文件路径
            SharedPreferences sharedPreferences = getSharedPreferences("MyOpto", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor;
            editor = sharedPreferences.edit();
            String user_code = MainActivity.getInstance().getUser().getUser_code();
            editor.putBoolean("isLogin",true);
            editor.putString("user_name",username);
            editor.putString("user_code",user_code);
            editor.putString(user_code+"_img_uri",uri);
            editor.commit();

            setResult(RESULT_OK);
            setTittle("修改成功", getResources().getColor(R.color.green), 1000, true);
            */
        }
    }

    /**
     * 配置顶部的按钮
     */
    private void setTittle( String text , int color , int time , final boolean isGone ){
        tittle.setText(text);
        tittle.setBackgroundColor(color);
        tittle.setVisibility(View.VISIBLE);

        if(time!=0) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tittle.setVisibility(View.GONE);
                    if (isGone)
                        finish();
                }
            }, time);
        }

    }

}
